package main

import (
	"context"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// bson中的key对应的是结构体中的标签，bson的value对应的是结构体的value

// startTime小于某时间
// {"$lt":timestamp}
type TimeBeforeCond struct {
	Before int64 `bson:"$lt"`
}

// {"timePoint.startTime":{"$lt":timestamp}}
type DeleteCond struct {
	beforeCond TimeBeforeCond `bson:"timePoint.startTime"`
}

func main() {
	// mongodb读取回来的是bson，需要反序列为LogRecord对象
	var (
		client     *mongo.Client
		err        error
		opt        *options.ClientOptions
		database   *mongo.Database
		collection *mongo.Collection
		delCond    *DeleteCond
		delResult  *mongo.DeleteResult
	)

	// 1.建立连接
	opt = options.Client() // 生成一个Clientopt
	opt.ApplyURI("mongodb://127.0.0.1:27017")
	opt.SetConnectTimeout(5 * time.Second)

	if client, err = mongo.Connect(context.TODO(), opt); err != nil {
		fmt.Println(err)
		return
	}

	// 2.选择数据库my_db
	database = client.Database("cron")

	// 3.选择表my_collection
	collection = database.Collection("log")

	// 4.要删除开始时间早于当前时间的所有日志($lt是less than)
	// 删除条件：delete({"timePoint.startTime":{"$lt":当前时间}})
	// 函数之间调用，尽量传地址，避免拷贝
	delCond = &DeleteCond{beforeCond: TimeBeforeCond{Before: time.Now().Unix()}}

	// 执行删除
	if delResult, err = collection.DeleteMany(context.TODO(), delCond); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("删除的行数：", delResult.DeletedCount)
}
